#!/bin/bash

DAEMON1="/myapp/reminder/venv/bin/uwsgi --ini /myapp/reminder/reminder/uwsgi.ini"
PIDFILE=/myapp/reminder/uwsgi.pid

function status {
  ps xf |grep "/myapp/reminder/venv/bin/uwsgi" |grep -v grep
  ps xf |grep "/myapp/reminder/venv/bin/celery" |grep -v grep
}


function start {
  cd /myapp/reminder/reminder
  $DAEMON1
  export C_FORCE_ROOT=true
  nohup /myapp/reminder/venv/bin/celery -A Reminder beat -l info --logfile /myapp/reminder/beat.log >/dev/null 2>&1 &
  nohup /myapp/reminder/venv/bin/celery -A Reminder worker -c 3 -l info --logfile /myapp/reminder/celery.log >/dev/null 2>&1 &
  nohup /myapp/reminder/venv/bin/celery -A Reminder worker -l info --autoscale=8,4 >/dev/null 2>&1 &
}


function stop {
  pid=$(ps aux |grep "venv/bin/uwsgi" |grep -v grep |awk '{print $2}' |xargs)
  if [[ ! -z "$pid" ]]; then
    kill -9 $pid >/dev/null 2>&1
    rm -rf $PIDFILE >/dev/null 2>&1
  fi
  pid=$(ps aux |grep "venv/bin/celery" |grep -v grep |awk '{print $2}' |xargs)
  if [[ ! -z "$pid" ]]; then
    kill -9 $pid >/dev/null 2>&1
    rm -rf $PIDFILE >/dev/null 2>&1
  fi
}

function reload {
  $DAEMON --reload $PIDFILE || echo -n "gunicorn can't reload"
}

case $1 in
  status)
    status
    ;;
  start)
    start
    status
    ;;
  reload)
   reload
   ;;
  stop)
    stop
    status
    ;;
  restart)
    stop
    status
    start
    status
    ;;
  *)
    echo "Usage: bash $0 {status|start|stop|restart|reload}"
    ;;
esac

